/**
 * 公共Modal
 */
import React from 'react';
import { message, Modal } from 'antd';

const WithModal = ({pathname}) => {
  return function WithModalFactory(WrappedComponent) {
		return class HOC extends React.Component {

			constructor(props) {
				super(props);
        this.dispatch = this.props.dispatch;
        this.state = {
          visible: false,
        };
      }

      showModelHandler = (e) => {
        this.props.form.resetFields();
        if (e) e.stopPropagation();
        this.setState({
          visible: true,
        });
      };

      hideModelHandler = () => {
        this.setState({
          visible: false,
        });
      };

      okHandler = (params, context) => {
        const { title, dispatch, namespace, option, record } = this.props;
        Modal.confirm({
          title: '系统提示',
          content: context || `确定${title}吗？`,
          okText: '确定',
          cancelText: '取消',
          onOk:() => {
            dispatch({
              type: `${namespace}/${option}`,
              payload: {...params, id:record.id}
            }).then((data) => {
              if(data) {
                this.setState({visible: false})
                message.info('操作成功')
                dispatch({type: pathname})
              }
            })
          }
        });
      };

			render() {
        const { loading, namespace, option } = this.props;
        const fetching = loading.effects[`${namespace}/${option}`];
				return (
					<WrappedComponent {...this.props} {...this.state} loading={fetching} showModelHandler={this.showModelHandler} hideModelHandler={this.hideModelHandler} okHandler={this.okHandler}/>
				)
			}
		}
	}
}
export default WithModal;
